package com.component.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.component.domain.MFile;
import com.component.mapper.MFIleMapper;
import com.component.service.MFileService;
import com.system.security.SecurityUtil;
import com.system.security.domain.SelfUserEntity;
import com.system.util.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/7/2 22:15
 * @since JDK 1.8
 */
@Service
public class MFileServiceImpl extends ServiceImpl<MFIleMapper, MFile> implements MFileService {

    @Override
    public JSONObject addFilesByPath(String path) {
        List<File> files=FileUtils.getFiles(path);
        if(!files.isEmpty()){
            SelfUserEntity selfUserEntity= SecurityUtil.getSelfUserEntity();
            List<MFile> mFiles=new ArrayList<>();
            for (File file : files) {
                MFile mFile=fileToMFile(selfUserEntity.getUserId().toString(),file);
                mFiles.add(mFile);
            }
            super.saveBatch(mFiles);
        }
        return null;
    }

    @Override
    public MFile fileToMFile(String uid, File file) {
        MFile mFile = new MFile();
        String fileType= FileUtils.getFileType(file);
        mFile.setFileName(file.getName());
        mFile.setFileType(fileType);
        mFile.setFileSize(file.length());
        mFile.setUid(uid);
        mFile.setFilePath(file.getPath());
        return mFile;
    }

    @Override
    public IPage<MFile> page(Integer page, Integer size, String keyword) {
        LambdaQueryWrapper<MFile> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(keyword)){
            queryWrapper.like(MFile::getFileName,keyword);
            queryWrapper.or().like(MFile::getFileType,keyword);
        }
        queryWrapper.orderByDesc(MFile::getCreateTime);
        IPage<MFile> pageData=this.baseMapper.selectPage(new Page(page,size),queryWrapper);
        return pageData;
    }

    @Override
    public IPage<MFile> pageByFileType(Integer pageNum, Integer pageSize, List<String> fileTypes) {
        LambdaQueryWrapper<MFile> queryWrapper = new LambdaQueryWrapper<>();
        if(fileTypes!=null && fileTypes.size() > 0){
            queryWrapper.in(MFile::getFileType,fileTypes);
        }
        queryWrapper.orderByDesc(MFile::getCreateTime);
        IPage<MFile> pageData=this.baseMapper.selectPage(new Page(pageNum,pageSize),queryWrapper);
        return pageData;

    }


}
